package org.xinjiang.tarim.travel.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.xinjiang.tarim.travel.model.File;
import org.xinjiang.tarim.travel.service.FileService;
import org.xinjiang.tarim.travel.utils.Constants;
import org.xinjiang.tarim.travel.utils.JsonResult;
import org.xinjiang.tarim.travel.utils.UploadFileUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api/file")
public class FileApi {
    @Autowired
    FileService service;

    /**
     * 批量上传
     * @param files
     * @return
     */
    @RequestMapping(value = "/uploadFiles")
    public JsonResult uploadFiles(MultipartFile[] files){
        JsonResult jsonResult;
        try {
            List<Map> list = UploadFileUtil.upload(files);
            List<File> fileList = JSONArray.parseArray(JSON.toJSONString(list), File.class);
            fileList = service.insert(fileList);
            jsonResult = new JsonResult(Constants.STATUS_SUCCESS,"上传成功"+fileList.size(), fileList);
        }catch (Exception e){
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "上传异常");
        }
        return jsonResult;
    }

    /**
     * 上传
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadFile")
    public JsonResult uploadFile(MultipartFile file){
        JsonResult jsonResult;
        try {
            Map map = UploadFileUtil.upload(file);
            File fileResult = JSON.parseObject(JSON.toJSONBytes(map), File.class);
            List list = new ArrayList();
            list.add(fileResult);
            list = service.insert(list);

            jsonResult = new JsonResult(Constants.STATUS_SUCCESS,"上传成功", list.get(0));
        }catch (Exception e){
            jsonResult = new JsonResult(Constants.STATUS_ERROR, "上传异常");
        }
        return jsonResult;
    }
}
